#!/usr/bin/python
# -*- coding: UTF-8 -*-

from docx import Document
from docx.shared import Inches, Pt, Cm
from docx.oxml.ns import qn
from docx.enum.text import WD_ALIGN_PARAGRAPH
from docx.enum.table import WD_ALIGN_VERTICAL, WD_ROW_HEIGHT_RULE

import json
import sys
import math
reload (sys)
sys.setdefaultencoding('utf-8')

#将word文档中的文字按作文纸格式重新排版输出
def wordsTable(fileName,outputFile,columnNum=15,emptyRow = False,hadTitle = True,titleExclude = True, paragraphIndent = 2):
	print '开始排版',fileName

	docFile = Document(fileName)
	
	words = []
	wordsTotal = 0
	for paragraph in docFile.paragraphs:
		#print(paragraph.text)
		wordsTotal += len(paragraph.text)
		paragraphWords = list(paragraph.text.strip())
		words.append(paragraphWords)
	
	#print json.dumps(words,encoding="utf-8",ensure_ascii=False)
	print ("共%d个段落,%d个字符") % (len(docFile.paragraphs), wordsTotal)

	print '开始创建新文档'
	output = Document()
	output.styles['Normal'].font.name = u'宋体'
	output.styles['Normal']._element.rPr.rFonts.set(qn('w:eastAsia'), u'宋体')

	if hadTitle and titleExclude :
		p = output.add_paragraph()
		#剧中
		p.paragraph_format.alignment = WD_ALIGN_PARAGRAPH.CENTER
		r = p.add_run(''.join(words[0]))
		r.font.size = Pt(16) #字体大小
		r.bold = True #加粗
		words.pop(0)
	elif hadTitle :
		titleWords = words[0]
		tl = len(titleWords)
		if tl<columnNum :
			c = columnNum-tl
			if (c % 2) == 0:
				indent = c/2
			else:
				indent = (c+1)/2
			for i in range(indent) :
				titleWords.insert(0,' ')
		words[0] = titleWords
	

	rows = math.ceil(wordsTotal/columnNum)
	if emptyRow:
		rows = rows * 2

	table = output.add_table(rows=int(rows), cols=columnNum, style='Table Grid')
	table.outofit = True
	table.alignment = WD_ALIGN_PARAGRAPH.CENTER
	line = 0 #行
	col = 0 #列
	for i, p in enumerate(words):
		print '处理第',i+1,'段落'
		if line>0 or not hadTitle or titleExclude:
			for j in range(paragraphIndent):
				col += 1

		for w in p:
			cell = table.cell(line,col)
			cell.text = w
			#上下剧中
			cell.vertical_alignment =  WD_ALIGN_VERTICAL.CENTER
			#行高 0.7厘米
			table.rows[line].height=Cm(0.7)

			#文字剧中
			p = cell.paragraphs[0]
			p.paragraph_format.alignment = WD_ALIGN_PARAGRAPH.CENTER
			
			if line==0 and hadTitle and not titleExclude:
				#标题样式
				p.runs[0].font.bold = True
				p.runs[0].font.size = Pt(14)
			else:
				#内容样式
				p.runs[0].font.size = Pt(12)

			col += 1
			if col >= columnNum:
				line += 1
				if(emptyRow):
					line += 1
				if line >= rows:
					table.add_row()
					if emptyRow:
						table.add_row()
				col = 0

		line += 1
		if(emptyRow):
			line += 1
		if line >= rows:
			table.add_row()
			if emptyRow:
				table.add_row()
		col = 0

	if emptyRow:
		for l in range(1, len(table.rows),2):
			if(l<table.rows):
				table.cell(l,0).merge(table.cell(l,columnNum-1)) #合并空格
				table.rows[l].height = Cm(0.2) #行高0.2厘米
				table.rows[l].height_rule = WD_ROW_HEIGHT_RULE.EXACTLY #行高为固定值

	print '保存文件'
	output.save(outputFile)



def main():
	#文件名，不要拓展名，仅支持docx格式
	files = ['《冬天》'] #['《冬天》','《春天》','《夏天》','秋天']

	columnNum = 15 #每行格子数
	emptyRow = True #隔一行来个空行
	hadTitle = True #第一段落是否为标题
	titleExclude = False #标题不放入表格
	paragraphIndent = 2 #段落前空几个字符

	for f in files:
		fileName = f+'.docx' #原word文件名，不要后缀
		outputFile = f + '_output.docx' #输出文件
		wordsTable(fileName, outputFile, columnNum, emptyRow, hadTitle, titleExclude, paragraphIndent )


if __name__ == "__main__":
	main()